package yu.zhou.njupt.pdsmigration.processers.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.lang3.StringUtils;

import yu.zhou.njupt.pdsmigration.processers.Processor;

/**
 * @author yu.zhou
 * 
 */
public class ImageProcessor implements Processor {

    public void process(Connection connection) throws Exception {
        Statement s = null;
        ResultSet rs = null;
        QueryRunner sqlRunner = null;
        String insertString = "INSERT INTO NEW_EPC_IMAGE_EXPAND (CODE, APPLICABLE_MODEL) VALUES(?, ?)";

        try {
            s = connection.createStatement();
            rs = s.executeQuery("SELECT * FROM NEW_EPC_IMAGE");
            sqlRunner = new QueryRunner();
            while (rs.next()) {
                String code = rs.getString("CODE");
                String applicableModelString = rs.getString("APPLICABLE_MODELS");

                if (StringUtils.isNotBlank(applicableModelString)) {
                    String[] applicableModels = applicableModelString.split(",");
                    String[][] data = new String[applicableModels.length][];
                    int i = 0;
                    for (String applicableModel : applicableModels) {
                        data[i] = new String[] { code, applicableModel };
                        i++;
                    }
                    sqlRunner.batch(connection, insertString, data);
                } // applicableModelString == null 的用sql导入
            }
            System.out.println("ImageProcessor Complete!");
        } catch (SQLException e) {
            System.out.println("ImageProcessor Failed!");
            throw e;
        } finally {
            DbUtils.closeQuietly(null, s, rs);
        }
    }

}
